// document.querySelector('.chat[data-chat=person2]').classList.add('active-chat');
// document.querySelector('.person[data-chat=person2]').classList.add('active');
// websocket
var userList = []
this_user = window.sessionStorage.getItem('username')
console.log(this_user)
window.onload = function () {
  //先判断浏览器是否支持websocket
  if ("WebSocket" in window) {
      alert("您的浏览器支持 WebSocket!");
      // 打开一个 web socket
      ws = new WebSocket("ws://127.0.0.1:8000/chat/link/");
      console.log(ws)
      ws.onopen = function () {
          // Web Socket 已连接上，使用 send() 方法尝试发送数据
        ws.send(`USER:${this_user}`);
              alert('ok')
      };
      //监听服务端是否有消息发送过来，当有消息时执行方法
      ws.onmessage = function (evt) {
          //获取服务器发来的消息
          var received_msg = evt.data;
          //显示消息
          // alert("收到消息："+received_msg)
          console.log(received_msg)
          msg_list = received_msg.split(':')
          user_list = []
          head = msg_list[0]
          info = msg_list[1]
          console.log(head)
          if (userList.includes(head)){
            createinfo(head,info)
          }else{
            createuser(head)
            createinfo(head,info)
          }

      };
      //关闭页面或其他行为导致与服务器断开链接是执行
      ws.onclose = function () {
          // 关闭 websocket
          alert("连接已关闭...");
      };
  } else {
      // 浏览器不支持 WebSocket
      alert("您的浏览器不支持 WebSocket!");
  }
}
// 动态效果
// 发送消息
function sendmsg() {
  // target_user = $('#target_user').val()
  target_user = $('.person.active').attr('data-chat')
  if (target_user){
  if(friends.all.length>0){
    target_user = $('.person.active').attr('data-chat')
    console.log('!!',target_user)
  }
  send_info = $("#input").val()
  console.log(this_user + ':'+target_user+':'+$("#input").val())
  $.post("/chat/send/",{msg:this_user + ':'+target_user+':'+$("#input").val()},function (result) {
      if(result.msg=="success"){
          alert("消息推送成功")
      }
  })

  $("#input").val('')
  console.log(target_user)
  console.log(userList)
  createinfo('self',send_info)
  // if (userList.includes(target_user)){
  //   createinfo('self',send_info)
  // }else{
  //   createuser(target_user)
  //   createinfo('self',send_info)
  // }

}else{
  alert('您还没有好友')
}}
var friends = {
  list: document.querySelector('ul.people'),
  all: document.querySelectorAll('.left .person'),
  name: '' },

chat = {
  container: document.querySelector('.container .right'),
  current: null,
  person: null,
  name: document.querySelector('.container .right .top .name') };
  console.log(friends.all)
  console.log(chat)
if(friends.all.length>=1){
  console.log('test')
    person = friends.all[0].dataset.chat
    document.querySelector(`.chat[data-chat=${person}]`).classList.add('active-chat');
    document.querySelector(`.person[data-chat=${person}]`).classList.add('active');
  }

// console.log(friends)
// console.log(friends.all[0].dataset.chat)
friends.all.forEach(function (f) {
  f.addEventListener('mousedown', function () {
    f.classList.contains('active') || setAciveChat(f);
  });
});

function setAciveChat(f) {
  friends.list.querySelector('.active').classList.remove('active');
  f.classList.add('active');
  chat.current = chat.container.querySelector('.active-chat');
  chat.person = f.getAttribute('data-chat');
  chat.current.classList.remove('active-chat');
  chat.container.querySelector('[data-chat="' + chat.person + '"]').classList.add('active-chat');
  friends.name = f.querySelector('.name').innerText;
  chat.name.innerHTML = friends.name;
}
function createuser_s(){
  var uid = $('#target_user').val()
  $('#target_user').val('')
  post_data = {'username':uid}
  $.ajax({
    url:'http://127.0.0.1:8000/chat/getuser',
    type:'post',
    data:JSON.stringify(post_data),
    contentType:'application/json',
    dataType:'json',
    success:function(res){
      if (res.code == 200){
        createuser(uid)
      }else{
        alert('该用户不存在')
      }}
  })

}

function createuser(uid){
  // uid = 'zezezi'
  // 将uid添加到用户列表中
  if (userList.includes(uid)){
    alert('好友已经存在了哦')
  }else{
  userList.push(uid)
  var userlist = document.getElementById('userlist')
  // 动态生成左侧好友选项
  userlist.innerHTML = userlist.innerHTML + `<li class="person" data-chat="${uid}"><img src="../../../static/chat_static/img/thomas.jpg" alt="" /><span class="name">${uid}    </span><span class="time">2:09 PM</span><span class="preview">I was wondering...</span></li>`
  var info = $('#right_top')
  // 为生成的好友动态生成对应聊天框
  info.after(`<div class="chat" data-chat="${uid}"></div>`)
  // 将所有好友项添加到friends对象中
  friends = {
    list: document.querySelector('ul.people'),
    all: document.querySelectorAll('.left .person'),
    name: '' }
    // 将所有聊天框添加到chat对象中
    chat = {
      container: document.querySelector('.container .right'),
      current: null,
      person: null,
      name: document.querySelector('.container .right .top .name') };
      console.log(friends.all)
      // 添加初始active和active-chat类
    if(friends.all.length==1){
      person = friends.all[0].dataset.chat
      document.querySelector(`.person[data-chat=${person}]`).classList.add('active');
      document.querySelector(`.chat[data-chat=${person}]`).classList.add('active-chat');

    }
    console.log(friends)
    // 给friends对象中的所有元素添加事件
    friends.all.forEach(function (f) {
      f.addEventListener('mousedown', function () {
        f.classList.contains('active') || setAciveChat(f);
      });
    });
    console.log(chat)
}}
//创建消息
function createinfo(user,data){
  console.log(user)
  // alert('createinfo')
  if (user == 'self'){
    $('.chat.active-chat').append(`<div class="bubble me">${data}</div>`)
  }else{
    // $('.chat.active-chat').append(`<div class="bubble you">${data}</div>`)
    $(`.chat[data-chat=${user}]`).append(`<div class="bubble you">${data}</div>`)
  }
  // var info = $('.right')
  // info.after(``)
}